import useStore  from '@/store';
import { createRouter, createWebHashHistory } from 'vue-router'
// 除了登录页面, 其他的一进来就加载首页, 所以不需要做懒加载
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue'
const router = createRouter({
  // 路由模式
  history: createWebHashHistory(),
  // 路由规则
  routes: [
    // 首页
    {
      path: '/',
      component: Layout,
      // 二级路由
      children: [
        // 首页
        {
          path: '',
          component: Home
        },
        // 一级分类
        {
          path: '/category/:id',
          component: () => import('@/views/category/index.vue')
        },
        // 二级分类
        {
          path: '/category/sub/:id',
          component: () => import('@/views/category/sub.vue')
        },
        // 商品详情
        {
          path: '/goods/:id',
          component: () => import('@/views/goods/index.vue')
        },
        // 购物车
        {
          path: '/cart',
          component: () => import('@/views/cart/index.vue')
        },
        // 结算页面
        {
          path: '/member/checkout',
          component: () => import('@/views/member/pay/checkout.vue')
        },
        // 订单
        {
          path: '/member/pay',
          component: () => import('@/views/member/pay/index.vue')
        }
      ]
    },
    // 登录页
    {
      path: '/login',
      component: () => import('@/views/login/index.vue')
    },
    // 测试页
    {
      path: '/demo',
      component: () => import('@/views/demo/index.vue')
    },
    // QQ登录回跳页
    {
      path: '/login/callback',
      component: () => import('@/views/login/callback.vue')
    },
    // 支付回跳页
    {
      path: '/pay/callback',
      component: () => import('@/views/member/pay/callback.vue')
    }
  ],
  // 滚动位置
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 }
  },
})

// 对于未登录的用户, 拦截/member开头的地址 
router.beforeEach((to, from, next) => {
  // 判断用户是否登录
  const { cart } = useStore()
  if (cart.isLogin) {
    next()
  } else {
    // startsWith('abc') 判断是否以abc开头
    if (to.path.includes('/member')) {
      // 拦截
      // next('/login')
      // $route.push({ path: '', params or query })
      // params 刷新丢失    -> 存在内存中
      // query  刷新不会丢失 -> 拼接在地址栏上
      next({
        path: '/login',
        query: {  
          redirectUrl: to.fullPath   // fullPath 包含查询参数
        }  
      })
    } else {
      next()
    }
  }
})


export default router